package com.rybbaby.tss.api.login;

import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.consts.CommonConsts;
import com.rybbaby.tss.core.redis.RedisClient;
import com.rybbaby.tss.core.utils.AppResponse;
import com.rybbaby.tss.core.utils.EncryptPasswordUtil;
import com.rybbaby.tss.core.utils.HttpUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.front.tssAppUser.entity.TssAppUser;
import com.rybbaby.tss.front.tssAppUser.service.ITssAppUserService;
import com.rybbaby.tss.platform.sysAdminUser.entity.SysAdminUser;
import com.rybbaby.tss.platform.sysAdminUser.service.ISysAdminUserService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author 雷春琼
 * @description 班级表管理
 * @createDate 2017-08-09 下午11:50:14
 */
@CrossOrigin
@RestController
@RequestMapping(value = "api/login", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public class LoginApi extends BaseController {


    private final static String redisVerificationCodePrefix = "redisVerificationCode_";

    @Autowired
    private ITssAppUserService tssAppUserService;
    @Autowired
    private ISysAdminUserService sysAdminUserService;

    /**
     * 验证手机号
     *
     * @param phoneNumber 电话
     * @return
     */
    @Token(validateSign = true)
    @RequestMapping(value = "validatePhoneNumber", method = RequestMethod.GET)
    public String validatePhoneNumber(@RequestParam String phoneNumber) {
        String resMsg = "手机号可使用!";
        int resCode = 200;
        try {
            //验证手机号格式
            if (!validatePhone(phoneNumber)) {
                resMsg = "手机号格式不正确!";
                return new AppResponse(resMsg, 301).jsonResponse(false);
            }
            List<TssAppUser> tssAppParentsList = tssAppUserService.findByProperty("phoneNum", phoneNumber);
            if (tssAppParentsList != null && !tssAppParentsList.isEmpty()) {
                resMsg = "您的手机号已经注册，若您忘记密码请使用忘记密码功能找回您的密码!";
                return new AppResponse(resMsg, 302).jsonResponse(false);
            }
        } catch (Exception e) {
            resCode = 500;
            resMsg = "服务器端异常!";
            e.printStackTrace();
        }
        return new AppResponse(resMsg, resCode).jsonResponse(false);
    }

    /**
     * 获取短信验证码
     *
     * @param phoneNumber 手机号
     * @return
     */
    @Token(validateSign = true)
    @RequestMapping(value = "sendPhoneValidateCode", method = RequestMethod.POST)
    public String sendPhoneValidateCode(@RequestParam String phoneNumber) {
        String resMsg = "发送短信成功!";
        int resCode = 200;
        Object result = "";
        String data = "";
        if (!validatePhone(phoneNumber)) {
            resMsg = "请正确输入手机号!";
            return new AppResponse(resMsg, 301).jsonResponse(false);
        }
        Integer verificationCode = (int) ((Math.random() * 9 + 1) * 100000);
        try {
            String content = "【红黄蓝 TSS】您的验证码是：" + verificationCode;
            //调用短信接口
            String url = "http://192.168.0.4:8180/api/gateway/common/sendSms";
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("phoneNum", phoneNumber);
            paramsMap.put("content", content);

            result = HttpUtil.httpGet(url, paramsMap, HttpUtil.ReturnType.String);

            //缓存6位验证码
            String key = redisVerificationCodePrefix + phoneNumber;
            RedisClient.set(key, verificationCode.toString());
            RedisClient.expire(key, 600);

            JSONObject jsonObject = JSONObject.fromObject(result);
            resCode = jsonObject.getInt("resCode");
            resMsg = jsonObject.getString("resMsg");
            data = jsonObject.getString("data");
            if (resCode == 200) {
                resMsg = "发送短信成功!";
                info("短信验证码：" + verificationCode);
            } else {
                resMsg = "发送短信失败!";
                resCode = 302;
            }
        } catch (Exception e) {
            resCode = 500;
            System.out.println("发送短信验证码异常,请稍后再试!" + e);
            e.printStackTrace();
        }
        return new AppResponse(resMsg, resCode).jsonResponse(false);
    }

    /**
     * 用户注册
     *
     * @param verificationCode 手机号验证码
     * @param phoneNumber      手机号
     * @param password         密码
     * @return
     */
    @Token(validateSign = true)
    @RequestMapping(value = "register", method = RequestMethod.POST)
    public String register(@RequestParam String verificationCode,
                           @RequestParam String phoneNumber,
                           @RequestParam String clientSystemType,
                           @RequestParam String password) {
        String resMsg = "注册成功!";
        int resCode = 200;
        try {
            String redisVerificationCode = RedisClient.get(redisVerificationCodePrefix + phoneNumber);
            if (StringUtils.isBlank(redisVerificationCode)) {
                resMsg = "改手机号未发送手机号验证码或验证码已超时，请重新获取!";
                return new AppResponse(resMsg, 302).jsonResponse(false);
            }
            //删除验证码
            RedisClient.del(redisVerificationCodePrefix + phoneNumber);
            if (!redisVerificationCode.equals(verificationCode)) {
                resMsg = "验证码不正确!";
                return new AppResponse(resMsg, 301).jsonResponse(false);
            }
            if (!password.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$")) {
                resMsg = "密码格式不正确,请输入8-16位英文数字混合密码!";
                return new AppResponse(resMsg, 301).jsonResponse(false);
            }
            List<TssAppUser> tssAppParentsList = tssAppUserService.findByProperty("phoneNum", phoneNumber);
            if (tssAppParentsList != null && !tssAppParentsList.isEmpty()) {
                resMsg = "您的手机号已经注册，若您忘记密码请使用忘记密码功能找回您的密码!";
                return new AppResponse(resMsg, 302).jsonResponse(false);
            }
            TssAppUser appUser = new TssAppUser();
            appUser.setCreateTime(new Timestamp(System.currentTimeMillis()));
            appUser.setPhoneNum(phoneNumber);
            appUser.setRegisterClientSysType(clientSystemType);
            Serializable newId = tssAppUserService.register(appUser);
            if (newId != null) {
                // 密码加密,用jdbc查询防止缓存
                String sql = "SELECT createTime FROM tss_app_user WHERE id=?";
                Map<String, Object> newstMatp = this.sysAdminUserService.findOneForJdbc(sql, new Object[]{newId});
                Object createTime = newstMatp.get("createTime");
                if (createTime != null && createTime instanceof Timestamp) {
                    String encryptPassword = EncryptPasswordUtil.encryptAdminPassword(newId.toString(), Timestamp.valueOf(createTime.toString()), password);
                    appUser = this.tssAppUserService.get(newId);
                    appUser.setPassword(encryptPassword);
                    this.tssAppUserService.updateEntitiy(appUser);
                }
                return new AppResponse(resMsg, resCode, appUser).jsonResponse(true);
            } else {
                resCode = 302;
                resMsg = "注册失败!";
                return new AppResponse(resMsg, resCode).jsonResponse(false);
            }
        } catch (Exception e) {
            return exceptionResponse(e);
        }
    }

    /**
     * 用户登录
     *
     * @param phoneNumber 手机号
     * @param password    密码
     * @return
     */
    @Token(validateSign = true)
    @RequestMapping(value = "appUserLogin", method = RequestMethod.POST)
    public String appUserLogin(@RequestParam String phoneNumber,
                               @RequestParam String password) {
        String resMsg = "登录成功!";
        int resCode = 200;
        try {
            //验证手机号格式
            if (!validatePhone(phoneNumber)) {
                resMsg = "手机号格式不正确!";
                return new AppResponse(resMsg, 301).jsonResponse(false);
            }
            List<TssAppUser> appUsers = tssAppUserService.findByProperty("phoneNum", phoneNumber);
            if (appUsers != null && !appUsers.isEmpty()) {
                TssAppUser appUser = appUsers.get(0);
                String encryptPassword = EncryptPasswordUtil.encryptAdminPassword(appUsers.get(0).getId(), appUsers.get(0).getCreateTime(), password);
                if (encryptPassword.equals(appUser.getPassword())) {
                    //登录成功
                    return new AppResponse(resMsg, resCode, appUser).jsonResponse(true);
                } else {
                    resMsg = "密码错误!";
                    resCode = 302;
                    return new AppResponse(resMsg, resCode).jsonResponse(false);
                }
            } else {
                resMsg = "账号不存在!";
                resCode = 302;
                return new AppResponse(resMsg, resCode).jsonResponse(false);
            }
        } catch (Exception e) {
            return exceptionResponse(e);
        }
    }

    /**
     * 教师端用户登录
     *
     * @param userName 用户名
     * @param password 密码
     * @return
     */
    @Token(validateSign = true)
    @RequestMapping(value = "appTeacherLogin", method = RequestMethod.POST)
    public String appTeacherLogin(@RequestParam String userName,
                                  @RequestParam String password) {
        String resMsg = "登录成功!";
        int resCode = 200;
        try {
            List<SysAdminUser> sysAdminUserList = sysAdminUserService.findByuserName(userName);
            if (sysAdminUserList != null && !sysAdminUserList.isEmpty()) {
                SysAdminUser sysAdminUser = sysAdminUserList.get(0);
                String encryptPassword = EncryptPasswordUtil.encryptAdminPassword(sysAdminUser.getId(), sysAdminUser.getCreateTime(), password);
                //查询登录
                if (encryptPassword.equals(sysAdminUser.getUserPassword())) {
                    //登录成功
                    return new AppResponse(resMsg, resCode, sysAdminUser).jsonResponse(true);
                } else {
                    resMsg = "账号或密码错误!";
                    resCode = 302;
                    return new AppResponse(resMsg, resCode).jsonResponse(false);
                }
            } else {
                resMsg = "此用户不存在";
                return new AppResponse(resMsg, 302).jsonResponse(false);
            }
        } catch (Exception e) {
            return exceptionResponse(e);
        }
    }

    /**
     * APP 端修改App修改密码
     *
     * @param verificationCode 手机号验证码
     * @param phoneNumber      手机号
     * @param newPassword      新密码
     * @return
     */
    @Token(validateSign = true)
    @RequestMapping(value = "changePassword", method = RequestMethod.POST)
    public String changePassword(@RequestParam String verificationCode,
                                 @RequestParam String phoneNumber,
                                 @RequestParam String newPassword) {
        String resMsg = "修改密码成功!";
        int resCode = 200;
        try {
            String redisVerificationCode = RedisClient.get(redisVerificationCodePrefix + phoneNumber);
            if (redisVerificationCode == null) {
                resMsg = "改手机号未发送手机号验证码或验证码已超时，请重新获取!";
                return new AppResponse(resMsg, 302).jsonResponse(false);
            }
            //删除验证码
            RedisClient.del(redisVerificationCodePrefix + phoneNumber);
            if (!redisVerificationCode.equals(verificationCode)) {
                resMsg = "验证码不正确!";
                return new AppResponse(resMsg, 301).jsonResponse(false);
            }
            //验证手机号格式
            if (!validatePhone(phoneNumber)) {
                resMsg = "手机号格式不正确!";
                return new AppResponse(resMsg, 301).jsonResponse(false);
            }
            //验证密码格式
            if (!newPassword.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$")) {
                resMsg = "密码格式不正确,请输入8-16位英文数字混合密码!";
                return new AppResponse(resMsg, 301).jsonResponse(false);
            }
            TssAppUser appUser = this.tssAppUserService.findUniqueByProperty("phoneNum", phoneNumber);
            if (appUser != null) {
                String encryptPassword = EncryptPasswordUtil.encryptAdminPassword(appUser.getId(), appUser.getCreateTime(), newPassword);
                appUser.setPassword(encryptPassword);
                this.tssAppUserService.updateEntitiy(appUser);
            } else {
                resMsg = "用户未注册!";
                return new AppResponse(resMsg, 302).jsonResponse(false);
            }
        } catch (Exception e) {
            resCode = 500;
            resMsg = "修改密码失败!";
            e.printStackTrace();
        }
        return new AppResponse(resMsg, resCode).jsonResponse(false);
    }

    /**
     * 异常响应
     *
     * @param e 异常对象
     * @return
     */
    private String exceptionResponse(Exception e) {
        e.printStackTrace();
        String message = e.getMessage();
        int resCode = 500;
        String resMsg = "服务器端异常" + (StringUtils.isNotBlank(message) ? ("(" + message + ")") : "") + "!";
        return new AppResponse(resMsg, resCode).jsonResponse(false);
    }

    /**
     * 验证手机号格式
     *
     * @param phone 手机号码
     * @return
     */
    private boolean validatePhone(String phone) {
        return StringUtils.isNotBlank(phone) && phone.matches(CommonConsts.PHONENUMBERREGEX);
    }
}